#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# @file: railgun/website/credential.py
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Contributors:
#   public@korepwx.com   <public@korepwx.com>
#   Dawei Yang           <davy.pristina@gmail.com>
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This file is released under BSD 2-clause license.

from flask import redirect, flash, request, url_for
from flask.ext.login import LoginManager, current_user
from flask.ext.babel import gettext as _

from entry.common.gravatar import get_avatar
from .models import LdapUser
from .context import app

# The global login manager for web application
login_manager = LoginManager()
login_manager.init_app(app)


@login_manager.user_loader
def __load_user_before_request(uid):
    user = LdapUser.query_by_uid(uid)
    return user


# Inject current user into template
@app.context_processor
def __inject_template_context():
    return dict(current_user=current_user)


# Response to unauthorized requests
@login_manager.unauthorized_handler
def unauthorized():
    flash(_('Please log in to access this page.'), 'danger')
    return redirect(url_for('signin', next=request.script_root + request.path))


# Inject `get_avatar` as `gravatar` filter into Jinja2 template engine.
app.template_filter('gravatar')(lambda user, size=24: get_avatar(user, size))
